<template>
  <div class="album-page">
    <!-- 搜索按钮放在页面标题右侧 -->
    <page-header
      title="我的相册"
      :subtitle="`${albumList.length} 个相册，共 ${totalPhotos} 张照片`"
    >
      <template #right>
        <!-- 搜索按钮 -->
        <el-button
          class="filter-btn"
          :class="{ 'is-active': showSearchPanel }"
          @click="toggleSearchPanel"
        >
          <el-icon><Filter /></el-icon>
          <span>筛选</span>
        </el-button>
        <el-button class="create-btn" @click="handleCreateAlbum">
          <el-icon><Plus /></el-icon>
          <span>新建相册</span>
        </el-button>
      </template>
    </page-header>

    <!-- 搜索面板改为弹窗 -->
    <el-dialog
      v-model="showSearchPanel"
      title="筛选条件"
      width="400px"
      :show-close="true"
      :close-on-click-modal="true"
      destroy-on-close
      class="search-dialog"
    >
      <el-form :model="searchForm" class="search-form" label-position="top">
        <!-- 关键词搜索 -->
        <el-form-item label="关键词">
          <el-input v-model="searchForm.name" placeholder="搜索相册名称/描述" clearable>
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <!-- 创建时间范围 -->
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="searchForm.createTimeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :shortcuts="dateShortcuts"
            value-format="YYYY-MM-DD"
            class="w-full"
          />
        </el-form-item>

        <!-- 相册状态 -->
        <el-form-item label="相册状态">
          <el-radio-group v-model="searchForm.status">
            <el-radio-button label="">全部</el-radio-button>
            <el-radio-button label="1">公开</el-radio-button>
            <el-radio-button label="0">私密</el-radio-button>
          </el-radio-group>
        </el-form-item>

        <!-- 排序方式 -->
        <el-form-item label="排序方式">
          <el-select v-model="searchForm.orderBy" class="w-full">
            <el-option label="自定义排序" value="orderNum asc" />
            <el-option label="创建时间倒序" value="createTime desc" />
            <el-option label="创建时间升序" value="createTime asc" />
            <el-option label="照片数量倒序" value="imgCount desc" />
            <el-option label="照片数量升序" value="imgCount asc" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleResetSearch" :loading="loading">重置</el-button>
          <el-button type="primary" @click="handleApplySearch" :loading="loading">
            应用筛选
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 右侧内容区域 -->
    <div class="main-content">
      <!-- 相册列表 -->
      <div class="album-container">
        <!-- 空状态 -->
        <el-empty v-if="!albumList.length" description="开始创建你的第一个相册吧" :image-size="180">
          <el-button class="create-btn" @click="handleCreateAlbum">
            <el-icon><Plus /></el-icon>
            <span>新建相册</span>
          </el-button>
        </el-empty>

        <!-- 相册网格 -->
        <div v-else class="album-grid">
          <div
            v-for="album in albumList"
            :key="album.id"
            class="album-card"
            @click="handleUpload(album)"
          >
            <div class="album-cover">
              <el-image :src="album.picUrl" fit="cover">
                <template #placeholder>
                  <div class="placeholder">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
                <template #error>
                  <div class="error">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>

              <!-- 相册信息 -->
              <div class="album-info">
                <div class="info-content">
                  <h3 class="name">{{ album.name }}</h3>
                  <p class="count">{{ album.imgCount || 0 }} 张照片</p>
                </div>
                <div class="actions">
                  <el-tooltip content="上传照片" placement="top">
                    <el-button circle @click.stop="handleUpload(album)">
                      <el-icon><Upload /></el-icon>
                    </el-button>
                  </el-tooltip>
                  <el-tooltip content="编辑相册" placement="top">
                    <el-button circle @click.stop="handleEdit(album)">
                      <el-icon><Edit /></el-icon>
                    </el-button>
                  </el-tooltip>
                  <el-tooltip content="删除相册" placement="top">
                    <el-button circle @click.stop="handleDelete(album)">
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </el-tooltip>
                </div>
              </div>

              <!-- 私密标记 -->
              <div v-if="album.status === '0'" class="private-badge">
                <el-icon><Lock /></el-icon>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页放在 album-container 外面 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pageNum"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[15, 30, 45, 60]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
        />
      </div>

      <!-- 相册表单抽屉 -->
      <el-drawer
        v-model="showFormDrawer"
        :title="formType === 'create' ? '新建相册' : '编辑相册'"
        size="500px"
        :destroy-on-close="true"
      >
        <el-form ref="formRef" :model="formData" :rules="formRules" label-position="top">
          <el-form-item label="相册名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入相册名称" />
          </el-form-item>

          <el-form-item label="相册封面" prop="picUrl">
            <el-upload
              class="cover-uploader"
              action="/commonApi/upload"
              :show-file-list="false"
              :before-upload="beforeCoverUpload"
              :on-success="handleCoverSuccess"
              :on-error="handleCoverError"
              accept="image/jpeg,image/png"
              :data="{
                filePath: 'album',
              }"
              name="file"
            >
              <div class="cover-container" :class="{ 'has-image': formData.picUrl }">
                <el-image
                  v-if="formData.picUrl"
                  :src="formData.picUrl"
                  fit="cover"
                  class="cover-preview"
                >
                  <template #error>
                    <div class="image-error">
                      <el-icon><Picture /></el-icon>
                    </div>
                  </template>
                </el-image>
                <div class="upload-overlay">
                  <el-icon class="upload-icon"><Plus /></el-icon>
                  <span>{{ formData.picUrl ? '更换封面' : '上传封面' }}</span>
                </div>
              </div>
            </el-upload>
            <div class="el-form-item__tip">建议尺寸 800x600 像素，支持 jpg、png 格式</div>
          </el-form-item>

          <el-form-item label="相册描述" prop="description">
            <el-input
              v-model="formData.description"
              type="textarea"
              :rows="3"
              placeholder="请输入相册描述"
            />
          </el-form-item>

          <el-form-item label="排序值" prop="orderNum">
            <el-input-number
              v-model="formData.orderNum"
              :min="0"
              :step="1"
              class="w-full"
              placeholder="请输入排序值"
            />
          </el-form-item>

          <el-form-item label="相册状态" prop="status">
            <el-radio-group v-model="formData.status">
              <el-radio value="1">公开</el-radio>
              <el-radio value="0">私密</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>

        <template #footer>
          <div class="drawer-footer">
            <el-button @click="showFormDrawer = false">取消</el-button>
            <el-button type="primary" :loading="submitting" @click="handleSubmit"> 确定 </el-button>
          </div>
        </template>
      </el-drawer>

      <!-- 上传图片抽屉 -->
      <el-drawer
        v-model="showUploadDrawer"
        :title="`上传到相册：${currentAlbum?.name || ''}`"
        size="800px"
        :destroy-on-close="true"
        class="upload-drawer"
      >
        <div class="upload-container">
          <!-- 上传区域 -->
          <div class="upload-zone">
            <el-upload ref="uploadRef" class="uploader" v-bind="uploadConfig" drag>
              <div class="upload-trigger">
                <el-icon class="upload-icon"><Upload /></el-icon>
                <div class="upload-text">
                  <h3>点击或拖拽图片到此区域上传</h3>
                  <p>支持 jpg、png、gif 格式，单个文件不超过 5MB</p>
                </div>
              </div>
            </el-upload>
          </div>

          <!-- 图片列表区域 -->
          <div class="image-section">
            <!-- 待上传列表 -->
            <div v-if="uploadFiles.length" class="upload-list">
              <div class="section-toolbar">
                <div class="toolbar-left">
                  <h3>待上传 ({{ uploadFiles.length }})</h3>
                </div>
                <div class="toolbar-right">
                  <el-button type="primary" @click="handleStartUpload" :loading="isUploading">
                    开始上传
                  </el-button>
                  <el-button @click="handleClearAll">清空列表</el-button>
                </div>
              </div>

              <div class="image-grid">
                <div v-for="file in uploadFiles" :key="file.uid" class="image-item">
                  <div class="image-card" :class="{ 'is-uploading': uploadProgress[file.uid] }">
                    <el-image :src="file.url" fit="cover">
                      <template #error>
                        <div class="image-error">
                          <el-icon><Picture /></el-icon>
                          <span>加载失败</span>
                        </div>
                      </template>
                    </el-image>

                    <!-- 上传进度 -->
                    <div v-if="uploadProgress[file.uid]" class="upload-progress">
                      <el-progress
                        type="circle"
                        :percentage="uploadProgress[file.uid]"
                        :width="32"
                        :stroke-width="4"
                      />
                    </div>

                    <div class="image-info">
                      <span class="name" :title="file.name">{{ file.name }}</span>
                      <span class="size">{{ formatSize(file.size) }}</span>
                    </div>

                    <div class="image-actions">
                      <el-button
                        circle
                        type="danger"
                        :icon="Delete"
                        @click="handleUploadRemove(file)"
                      />
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 已上传列表 -->
            <div class="uploaded-list">
              <div class="section-toolbar">
                <div class="toolbar-left">
                  <h3>已上传图片 ({{ imageList.length }})</h3>
                  <div class="search-box" :class="{ 'is-active': isSearchActive }">
                    <el-input
                      v-model="searchKeyword"
                      placeholder="搜索图片..."
                      clearable
                      @blur="handleSearchBlur"
                    >
                      <template #prefix>
                        <el-icon><Search /></el-icon>
                      </template>
                    </el-input>
                    <el-button
                      class="search-trigger"
                      :class="{ hide: isSearchActive }"
                      circle
                      @click="handleSearchClick"
                    >
                      <el-icon><Search /></el-icon>
                    </el-button>
                  </div>
                </div>
                <div class="toolbar-right">
                  <el-button-group>
                    <el-button
                      :icon="Refresh"
                      :loading="imageLoading"
                      @click="fetchAlbumImages(currentAlbum)"
                    >
                      刷新
                    </el-button>
                  </el-button-group>
                </div>
              </div>

              <div v-loading="imageLoading" class="image-grid">
                <template v-if="filteredAlbumImages.length">
                  <div v-for="image in filteredAlbumImages" :key="image.id" class="image-item">
                    <div class="image-card">
                      <el-image :src="image.url" fit="cover">
                        <template #placeholder>
                          <div class="image-placeholder">
                            <el-icon><Picture /></el-icon>
                          </div>
                        </template>
                      </el-image>

                      <div class="image-info">
                        <span class="name" :title="image.name">{{ image.name }}</span>
                        <span class="size">{{ formatSize(image.size) }}</span>
                      </div>

                      <div class="image-actions">
                        <el-button-group class="action-group">
                          <el-tooltip content="预览图片" placement="top">
                            <el-button
                              circle
                              :icon="View"
                              @click="(e) => handlePreviewImage(image, e)"
                            />
                          </el-tooltip>
                          <el-tooltip content="重命名图片" placement="top">
                            <el-button
                              circle
                              :icon="EditPen"
                              @click="(e) => handleRenameImage(image, e)"
                            />
                          </el-tooltip>
                          <el-tooltip content="删除图片" placement="top">
                            <el-button
                              circle
                              type="danger"
                              :icon="Delete"
                              @click="(e) => handleDeleteImage(image, e)"
                            />
                          </el-tooltip>
                        </el-button-group>
                      </div>
                    </div>
                  </div>
                </template>

                <!-- 空状态 -->
                <div v-else class="empty-state">
                  <el-empty
                    :description="searchKeyword ? '没有找到匹配的图片' : '相册还没有图片'"
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-drawer>

      <!-- 图片预览组件 -->
      <el-image-viewer
        v-if="previewVisible"
        :url-list="[previewUrl]"
        @close="previewVisible = false"
        :initial-index="0"
        :hide-on-click-modal="true"
        :zoom-rate="1.2"
        :min-scale="0.2"
        :max-scale="7"
      />

      <!-- 图片重命名弹窗 -->
      <el-dialog
        v-model="showRenameDialog"
        title="重命名图片"
        width="400px"
        :show-close="true"
        :close-on-click-modal="false"
        destroy-on-close
        class="rename-dialog"
      >
        <div class="rename-content">
          <div class="image-preview">
            <el-image
              v-if="currentRenameImage"
              :src="currentRenameImage.url"
              fit="cover"
              class="preview-image"
            >
              <template #error>
                <div class="image-error">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
          </div>

          <el-form
            ref="renameForm"
            :model="renameFormData"
            :rules="renameRules"
            label-position="top"
            class="rename-form"
          >
            <el-form-item label="图片名称" prop="prefix">
              <div class="name-input-wrapper">
                <el-input
                  v-model="renameFormData.prefix"
                  placeholder="请输入图片名称"
                  clearable
                  maxlength="80"
                  show-word-limit
                  class="prefix-input"
                  :show-clear-icon="false"
                />
                <span class="suffix-display">{{ renameFormData.suffix }}</span>
              </div>
              <div class="input-tip">
                只能修改文件名前缀，后缀（{{ renameFormData.suffix }}）保持不变
              </div>
            </el-form-item>
          </el-form>
        </div>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="handleCancelRename">取消</el-button>
            <el-button type="primary" @click="handleConfirmRename" :loading="submitting">
              保存
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, nextTick, onMounted, onBeforeUnmount, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { albumApi } from '@/api/album'
import {
  Plus,
  Picture,
  Upload,
  Edit,
  View,
  Delete,
  Lock,
  Refresh,
  Search,
  Select,
  Filter,
  EditPen,
} from '@element-plus/icons-vue'
import { useDebounceFn, useThrottleFn } from '@vueuse/core'
import { ElImageViewer } from 'element-plus'
import PageHeader from '@/components/PageHeader/index.vue'

// 状态定义
const loading = ref(false)
const submitting = ref(false)
const uploading = ref(false)
const showFormDrawer = ref(false)
const showUploadDrawer = ref(false)
const formType = ref('create')
const currentAlbum = ref(null)
const uploadFiles = ref([])
const formRef = ref(null)
const uploadRef = ref(null)
const isSearchActive = ref(false)
const searchKeyword = ref('')
const selectedImages = ref([])
const previewVisible = ref(false)
const previewUrl = ref('')
const pageNum = ref(1)
const pageSize = ref(15)
const total = ref(0)
const albumList = ref([])
const showSearchPanel = ref(false)
const uploadProgress = ref({}) // 存储每个文件的上传进度
const isUploading = ref(false)
const imageList = ref([])
const imageLoading = ref(false)
const showRenameDialog = ref(false)
const renameForm = ref(null)
const currentRenameImage = ref(null)
const renameFormData = reactive({
  prefix: '',
  suffix: '',
})

// 表单数据
const formData = reactive({
  name: '',
  picUrl: '',
  description: '',
  orderNum: 5,
  status: '1',
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入相册名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
  ],
  picUrl: [{ required: true, message: '请上传相册封面', trigger: 'change' }],
}

// 重命名表单验证规则
const renameRules = {
  prefix: [
    { required: true, message: '请输入图片名称', trigger: 'blur' },
    { min: 1, max: 80, message: '长度在 1 到 80 个字符', trigger: 'blur' },
    { pattern: /^[^<>:"/\\|?*]+$/, message: '文件名不能包含特殊字符', trigger: 'blur' },
  ],
}

// 搜索表单数据
const searchForm = reactive({
  name: '',
  createTimeRange: [],
  status: '',
  orderBy: 'orderNum asc',
})

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: '最近一月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
  {
    text: '最近三月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    },
  },
]

// 计算总照片数
const totalPhotos = computed(() => {
  return albumList.value.reduce((total, album) => total + album.imgCount, 0)
})

// 方法定义
const handleCreateAlbum = () => {
  formType.value = 'create'
  Object.assign(formData, {
    name: '',
    picUrl: '',
    description: '',
    orderNum: 5,
    status: '1',
  })
  showFormDrawer.value = true
}

const handleEdit = (album) => {
  formType.value = 'edit'
  Object.assign(formData, {
    id: album.id,
    name: album.name,
    picUrl: album.picUrl,
    description: album.description,
    orderNum: album.orderNum,
    status: album.status,
  })
  showFormDrawer.value = true
}

const handleDelete = async (album) => {
  try {
    await ElMessageBox.confirm('确定要删除该相册吗？', '提示', {
      type: 'warning',
    })
    loading.value = true
    await albumApi.deleteAlbum([album.id])
    ElMessage.success('删除成功')
    fetchAlbumList() // 刷新列表
  } catch (error) {
    console.error(error)
    ElMessage.error('删除失败')
  } finally {
    loading.value = false
  }
}

const handleUpload = (album) => {
  currentAlbum.value = album
  // 重置上传相关的状态
  uploadFiles.value = []
  uploadProgress.value = {}
  showUploadDrawer.value = true
}

const handleViewAlbum = (album) => {
  // TODO: 查看相册详情
  console.log('查看相册：', album)
}

// 移除单个文件
const handleUploadRemove = (file) => {
  const index = uploadFiles.value.findIndex((f) => f.uid === file.uid)
  if (index !== -1) {
    // 释放创建的 URL
    if (file.url && file.url.startsWith('blob:')) {
      URL.revokeObjectURL(file.url)
    }
    uploadFiles.value.splice(index, 1)
    delete uploadProgress.value[file.uid]
  }
}

// 清空上传列表
const handleClearAll = () => {
  // 释放所有创建的 URL
  uploadFiles.value.forEach((file) => {
    if (file.url && file.url.startsWith('blob:')) {
      URL.revokeObjectURL(file.url)
    }
  })
  uploadFiles.value = []
  uploadProgress.value = {}
}

// 处理文件变化
const handleUploadChange = (file, fileList) => {
  // 只处理新添加的文件
  if (file.status === 'ready') {
    // 验证文件类型
    const isImage = file.raw.type.startsWith('image/')
    if (!isImage) {
      ElMessage.error('只能上传图片文件')
      return false
    }

    // 验证文件大小（5MB）
    const isLt5M = file.size / 1024 / 1024 < 5
    if (!isLt5M) {
      ElMessage.error('图片大小不能超过 5MB')
      return false
    }

    // 创建新文件的 URL
    const url = URL.createObjectURL(file.raw)

    // 只添加当前新文件到待上传列表
    uploadFiles.value = [
      ...uploadFiles.value,
      {
        ...file,
        url,
        status: 'ready',
      },
    ]
  }
}

// 修改上传组件配置 - 移到函数定义后面
const uploadConfig = {
  multiple: true,
  autoUpload: false,
  showFileList: false,
  accept: 'image/jpeg,image/png,image/gif',
  onRemove: handleUploadRemove,
  onChange: handleUploadChange,
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitting.value = true

    const data = {
      ...formData,
      picUrl: formData.picUrl,
      orderNum: formData.orderNum || 5,
    }

    if (formType.value === 'create') {
      await albumApi.addAlbum(data)
      ElMessage.success('创建成功')
    } else {
      await albumApi.updateAlbum(data)
      ElMessage.success('更新成功')
    }

    showFormDrawer.value = false
    fetchAlbumList() // 刷新列表
  } catch (error) {
    console.error(error)
    ElMessage.error('保存失败')
  } finally {
    submitting.value = false
  }
}

const handleStartUpload = async () => {
  if (!uploadFiles.value.length) {
    ElMessage.warning('请先选择要上传的图片')
    return
  }

  try {
    isUploading.value = true
    const formData = new FormData()

    // 保存当前待上传的文件列表
    const currentFiles = [...uploadFiles.value]

    currentFiles.forEach((file) => {
      formData.append('files', file.raw)
    })

    formData.append('filePath', 'album/')
    formData.append('albumId', currentAlbum.value.id)

    const res = await albumApi.uploadPic(formData, {
      onUploadProgress: (progressEvent) => {
        const progress = Math.round((progressEvent.loaded * 100) / progressEvent.total)
        currentFiles.forEach((file) => {
          uploadProgress.value[file.uid] = progress
        })
      },
    })

    if (res && res.length) {
      ElMessage.success('上传成功')
      // 清空上传列表和进度
      handleClearAll()
      // 刷新相册图片列表
      await fetchAlbumImages(currentAlbum.value)
      // 刷新相册列表以更新图片数量
      await fetchAlbumList()
    }
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('上传失败，请重试')
  } finally {
    isUploading.value = false
  }
}

// 格式化文件大小
const formatSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return `${(bytes / Math.pow(k, i)).toFixed(1)} ${sizes[i]}`
}

// 分离文件名前缀和后缀
const splitFileName = (fileName) => {
  const lastDotIndex = fileName.lastIndexOf('.')
  if (lastDotIndex === -1) {
    return { prefix: fileName, suffix: '' }
  }
  return {
    prefix: fileName.substring(0, lastDotIndex),
    suffix: fileName.substring(lastDotIndex),
  }
}

// 合并文件名前缀和后缀
const joinFileName = (prefix, suffix) => {
  return prefix + suffix
}

// 删除单张图片
const handleDeleteImage = async (image, e) => {
  e.stopPropagation() // 阻止事件冒泡，避免触发预览

  try {
    await ElMessageBox.confirm('确定要删除这张图片吗？删除后不可恢复', '删除确认', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    })

    loading.value = true
    const res = await albumApi.deletePic([image.id])

    if (res) {
      ElMessage.success('删除成功')
      // 刷新图片列表
      await fetchAlbumImages(currentAlbum.value)
      // 刷新相册列表以更新图片数量
      await fetchAlbumList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除图片失败:', error)
      ElMessage.error('删除失败，请重试')
    }
  } finally {
    loading.value = false
  }
}

const handleSearchClick = () => {
  isSearchActive.value = true
  // 使用 nextTick 确保输入框已渲染
  nextTick(() => {
    // 找到输入框并聚焦
    const input = document.querySelector('.search-box .el-input__inner')
    if (input) {
      input.focus()
    }
  })
}

const handleSearchBlur = () => {
  if (!searchKeyword.value) {
    isSearchActive.value = false
  }
}

const handleImageSelect = (image) => {
  const index = selectedImages.value.indexOf(image.id)
  if (index > -1) {
    selectedImages.value.splice(index, 1)
  } else {
    selectedImages.value.push(image.id)
  }
}

const handleBatchDeleteImages = async (images) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${images.length} 张图片吗？删除后不可恢复`,
      '批量删除确认',
      {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      },
    )

    loading.value = true
    const ids = images.map((img) => img.id)
    const res = await albumApi.deletePic(ids)

    if (res) {
      ElMessage.success('删除成功')
      // 刷新图片列表
      await fetchAlbumImages(currentAlbum.value)
      // 刷新相册列表以更新图片数量
      await fetchAlbumList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除图片失败:', error)
      ElMessage.error('删除失败，请重试')
    }
  } finally {
    loading.value = false
  }
}

// 添加预览方法
const handlePreviewImage = (image, event) => {
  event.stopPropagation() // 阻止事件冒泡
  previewUrl.value = image.url
  previewVisible.value = true
}

// 处理图片重命名
const handleRenameImage = (image, event) => {
  event.stopPropagation() // 阻止事件冒泡
  currentRenameImage.value = image

  // 分离文件名前缀和后缀
  const { prefix, suffix } = splitFileName(image.name)
  renameFormData.prefix = prefix
  renameFormData.suffix = suffix

  showRenameDialog.value = true
}

// 取消重命名
const handleCancelRename = () => {
  showRenameDialog.value = false
  currentRenameImage.value = null
  renameFormData.prefix = ''
  renameFormData.suffix = ''
  if (renameForm.value) {
    renameForm.value.clearValidate()
  }
}

// 确认重命名
const handleConfirmRename = async () => {
  if (!renameForm.value || !currentRenameImage.value) return

  try {
    await renameForm.value.validate()

    // 合并新的文件名
    const newFileName = joinFileName(renameFormData.prefix, renameFormData.suffix)

    // 检查名称是否发生变化
    if (newFileName === currentRenameImage.value.name) {
      ElMessage.warning('新名称与当前名称相同')
      return
    }

    submitting.value = true
    const res = await albumApi.renamePic(currentRenameImage.value.id, newFileName)

    ElMessage.success('重命名成功')
    // 更新本地图片列表中的名称
    const imageIndex = imageList.value.findIndex((img) => img.id === currentRenameImage.value.id)
    if (imageIndex !== -1) {
      imageList.value[imageIndex].name = newFileName
    }
    // 自动关闭弹窗
    handleCancelRename()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('重命名失败:', error)
      ElMessage.error('重命名失败，请重试')
    }
  } finally {
    submitting.value = false
  }
}

// 重置搜索条件
const handleResetSearch = async () => {
  try {
    loading.value = true
    // 重置表单数据
    Object.assign(searchForm, {
      name: '',
      createTimeRange: [],
      status: '',
      orderBy: 'createTime desc',
    })
    pageNum.value = 1 // 重置页码
    await fetchAlbumList() // 获取重置后的数据
    showSearchPanel.value = false // 关闭弹窗
  } catch (error) {
    console.error('重置筛选失败:', error)
    ElMessage.error('重置筛选失败')
  } finally {
    loading.value = false
  }
}

// 应用筛选
const handleApplySearch = async () => {
  try {
    loading.value = true
    pageNum.value = 1 // 重置页码
    await fetchAlbumList() // 获取筛选后的数据
    showSearchPanel.value = false // 关闭弹窗
  } catch (error) {
    console.error('应用筛选失败:', error)
    ElMessage.error('应用筛选失败')
  } finally {
    loading.value = false
  }
}

// 修改获取列表方法，添加搜索参数
const fetchAlbumList = async () => {
  try {
    loading.value = true
    const res = await albumApi.getList({
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      name: searchForm.name,
      createTimeRange: searchForm.createTimeRange,
      status: searchForm.status,
      orderBy: searchForm.orderBy,
    })
    albumList.value = res.records
    total.value = res.total
  } catch (error) {
    console.error('获取相册列表失败:', error)
    ElMessage.error('获取相册列表失败')
  } finally {
    loading.value = false
  }
}

// 上传成功的处理
const handleCoverSuccess = (res) => {
  if (res.code === 1) {
    formData.picUrl = res.data
    ElMessage.success('上传成功')
  } else {
    ElMessage.error(res.message || '上传失败')
  }
}

// 上传失败的处理
const handleCoverError = (error) => {
  console.error('上传失败:', error)
  ElMessage.error('上传失败')
}

// 上传前的校验
const beforeCoverUpload = (file) => {
  const isImage = /^image\/(jpeg|png)$/.test(file.type)
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传 JPG/PNG 格式的图片!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 处理每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val
  pageNum.value = 1 // 重置到第一页
  fetchAlbumList()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  pageNum.value = val
  fetchAlbumList()
}

// 切换搜索面板显示/隐藏
const toggleSearchPanel = () => {
  showSearchPanel.value = !showSearchPanel.value
}

// 获取相册图片列表
const fetchAlbumImages = async (album) => {
  if (!album?.id) return

  try {
    imageLoading.value = true
    const res = await albumApi.getPicList(album.id)

    // 处理返回的数据
    imageList.value = res.map((item) => ({
      id: item.id,
      name: item.picName,
      url: item.picUrl,
      size: item.picSize,
      createTime: item.createTime,
      updateTime: item.updateTime,
    }))
  } catch (error) {
    console.error('获取相册图片失败:', error)
    ElMessage.error('获取相册图片失败')
  } finally {
    imageLoading.value = false
  }
}

// 监听当前相册变化
watch(
  () => currentAlbum.value,
  (newAlbum) => {
    if (newAlbum) {
      fetchAlbumImages(newAlbum)
    } else {
      imageList.value = []
    }
  },
)

// 处理图片列表展示
const filteredAlbumImages = computed(() => {
  if (!imageList.value.length) return []

  // 如果有搜索关键词，进行过滤
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    return imageList.value.filter((image) => image.name.toLowerCase().includes(keyword))
  }

  return imageList.value
})

// 页面加载时获取数据
onMounted(() => {
  fetchAlbumList()
})

// 组件卸载时清理
onBeforeUnmount(() => {
  handleClearAll()
})

// 监听抽屉关闭
watch(
  () => showUploadDrawer.value,
  async (newVal) => {
    if (!newVal) {
      // 抽屉关闭时清空上传列表
      handleClearAll()
      // 刷新相册列表以更新图片数量
      await fetchAlbumList()
    }
  },
)
</script>

<style lang="scss" scoped>
// 导入主题变量和混合器
@use '@/assets/styles/theme/base.scss' as *;
@use '@/assets/styles/mixins.scss' as *;
@use 'sass:color';

.album-page {
  min-height: 100%;
  height: 100%;
  background: linear-gradient(135deg, #f5f7fa 0%, #f7f9fc 100%);
  padding: 24px;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  // 新建按钮样式
  .create-btn {
    background: linear-gradient(
      135deg,
      $color-primary,
      color.adjust($color-primary, $lightness: 10%)
    );
    border: none;
    padding: 12px 24px;
    font-weight: 500;
    color: white;
    transition: all 0.3s ease;
    border-radius: 8px;
    letter-spacing: 0.5px;

    .el-icon {
      margin-right: 6px;
      font-size: 16px;
      vertical-align: -1px;
    }

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 6px 16px rgba($color-primary, 0.4);
      background: linear-gradient(
        135deg,
        color.adjust($color-primary, $lightness: 5%),
        color.adjust($color-primary, $lightness: 15%)
      );
    }

    &:active {
      transform: translateY(0);
      box-shadow: 0 2px 8px rgba($color-primary, 0.3);
      background: linear-gradient(
        135deg,
        color.adjust($color-primary, $lightness: -5%),
        $color-primary
      );
    }
  }

  // 右侧内容区域
  .main-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-height: 0;
  }

  // 相册容器
  .album-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    margin: 10px 0;
    overflow-y: auto;
    min-height: 0;
    padding-right: 8px;

    // 添加滚动条美化样式
    &::-webkit-scrollbar {
      width: 8px;
      height: 8px;
    }

    &::-webkit-scrollbar-track {
      background: transparent;
      border-radius: 4px;
      margin: 4px 0;
    }

    &::-webkit-scrollbar-thumb {
      background: rgba($color-primary, 0.1);
      border-radius: 4px;
      border: 2px solid transparent;
      background-clip: content-box;
      transition: all 0.3s ease;

      &:hover {
        background: rgba($color-primary, 0.2);
        background-clip: content-box;
      }
    }

    // Firefox 滚动条样式
    scrollbar-width: thin;
    scrollbar-color: rgba($color-primary, 0.1) transparent;

    // 隐藏水平滚动条
    overflow-x: hidden;

    // 相册网格
    .album-grid {
      flex: 1;
      display: grid;
      grid-template-columns: repeat(5, 1fr);
      grid-auto-rows: min-content;
      gap: 16px;
      padding-bottom: 24px;

      // 相册卡片
      .album-card {
        border-radius: 12px;
        overflow: hidden;
        background: $bg-base;
        box-shadow: 0 8px 24px rgba(0, 0, 0, 0.04);
        transition: all 0.3s ease;
        cursor: pointer;

        &:hover {
          transform: translateY(-4px);
          box-shadow: 0 12px 32px rgba(0, 0, 0, 0.1);

          .album-cover {
            .el-image {
              transform: scale(1.08);
            }

            .album-info {
              background: linear-gradient(to top, rgba(0, 0, 0, 0.85), rgba(0, 0, 0, 0.2));
              .actions {
                opacity: 1;
                transform: translateY(0);
              }
            }
          }
        }

        .album-cover {
          position: relative;
          width: 100%;
          padding-bottom: 66.67%; // 保持 3:2 比例

          .el-image {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            transition: transform 0.5s cubic-bezier(0.4, 0, 0.2, 1);
          }

          // 相册信息
          .album-info {
            position: absolute;
            left: 0;
            right: 0;
            bottom: 0;
            padding: 20px;
            background: linear-gradient(to top, rgba(0, 0, 0, 0.75), rgba(0, 0, 0, 0));
            color: white;
            transition: all 0.3s ease;

            .info-content {
              .name {
                font-size: 20px;
                font-weight: 500;
                margin: 0;
                line-height: 1.4;
                text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
              }

              .count {
                font-size: 14px;
                margin: 4px 0 0;
                opacity: 0.9;
                text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
              }
            }

            .actions {
              position: absolute;
              right: 16px;
              bottom: 16px;
              display: flex;
              gap: 8px;
              opacity: 0;
              transform: translateY(10px);
              transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);

              .el-button {
                background: rgba(255, 255, 255, 0.2);
                border: none;
                padding: 8px;
                font-size: 16px;
                color: white;
                backdrop-filter: blur(4px);
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);

                &:hover {
                  background: rgba(255, 255, 255, 0.3);
                  transform: translateY(-2px);
                  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
                }

                &:active {
                  transform: translateY(0);
                  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
                }
              }
            }
          }

          // 私密标记
          .private-badge {
            position: absolute;
            top: 12px;
            right: 12px;
            width: 32px;
            height: 32px;
            border-radius: 50%;
            background: rgba(0, 0, 0, 0.6);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 16px;
            backdrop-filter: blur(4px);
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
          }
        }
      }
    }
  }

  // 分页容器
  .pagination-container {
    flex-shrink: 0;
    margin-top: 10px;
    padding: 12px 24px;
    display: flex;
    justify-content: center;
    background: linear-gradient(to bottom, transparent, rgba($bg-base, 0.8));
    backdrop-filter: blur(10px);
    border-radius: 12px;

    :deep(.el-pagination) {
      .el-pagination__total,
      .el-pagination__sizes {
        font-size: 14px;
        color: $text-secondary;
      }

      .btn-prev,
      .btn-next {
        background: transparent;

        &:hover {
          color: $color-primary;
        }
      }

      .el-pager li {
        background: transparent;
        border: 1px solid transparent;
        transition: all 0.3s ease;

        &:hover {
          color: $color-primary;
          border-color: rgba($color-primary, 0.1);
          background: rgba($color-primary, 0.05);
        }

        &.is-active {
          background: rgba($color-primary, 0.1);
          color: $color-primary;
          font-weight: 600;
          border-color: rgba($color-primary, 0.2);
        }
      }

      .el-pagination__sizes {
        .el-select {
          .el-input {
            .el-input__inner {
              background: transparent;
              border-color: $border-light;

              &:hover {
                border-color: $color-primary;
              }
            }
          }
        }
      }

      .el-pagination__jump {
        color: $text-secondary;

        .el-input__inner {
          background: transparent;
          border-color: $border-light;

          &:hover {
            border-color: $color-primary;
          }
        }
      }
    }
  }
}

// 修改响应式布局断点
@media screen and (max-width: 1800px) {
  .album-grid {
    grid-template-columns: repeat(4, 1fr) !important;
  }
}

@media screen and (max-width: 1400px) {
  .album-grid {
    grid-template-columns: repeat(3, 1fr) !important;
  }
}

@media screen and (max-width: 1000px) {
  .album-grid {
    grid-template-columns: repeat(2, 1fr) !important;
  }
}

@media screen and (max-width: 768px) {
  .album-grid {
    grid-template-columns: 1fr !important;
  }
}

// 上传抽屉样式
.upload-drawer {
  :deep(.el-drawer__body) {
    padding: 0;
    height: calc(100% - 53px);
    overflow: hidden;
  }
}

.upload-container {
  height: 100%;
  padding: 24px;
  overflow-y: auto;
  background: $bg-light;

  // 上传区域
  .upload-zone {
    background: $bg-base;
    border-radius: 12px;
    padding: 24px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);

    .uploader {
      :deep(.el-upload) {
        width: 100%;
      }

      :deep(.el-upload-dragger) {
        width: 100%;
        height: 140px;
        border: 2px dashed rgba($color-primary, 0.2);
        border-radius: 8px;
        background: linear-gradient(135deg, rgba($color-primary, 0.02), rgba($color-primary, 0.05));
        transition: all 0.3s ease;

        &:hover {
          border-color: $color-primary;
          background: linear-gradient(
            135deg,
            rgba($color-primary, 0.05),
            rgba($color-primary, 0.08)
          );

          .upload-icon {
            transform: translateY(-5px);
            color: $color-primary;
          }
        }

        .upload-trigger {
          height: 100%;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          gap: 12px;

          .upload-icon {
            font-size: 32px;
            color: rgba($color-primary, 0.6);
            transition: all 0.3s ease;
          }

          .upload-text {
            text-align: center;

            h3 {
              font-size: 16px;
              font-weight: 500;
              color: $text-primary;
              margin: 0 0 4px;
            }

            p {
              font-size: 13px;
              color: $text-secondary;
              margin: 0;
            }
          }
        }
      }
    }
  }

  // 图片列表区域
  .image-section {
    margin-top: 24px;
    display: flex;
    flex-direction: column;
    gap: 24px;

    // 待上传列表
    .upload-list {
      background: $bg-base;
      border-radius: 12px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
    }

    // 已上传列表
    .uploaded-list {
      background: $bg-base;
      border-radius: 12px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
    }

    // 工具栏样式
    .section-toolbar {
      padding: 16px 20px;
      border-bottom: 1px solid $border-lighter;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .toolbar-left {
        display: flex;
        align-items: center;
        gap: 12px;

        h3 {
          margin: 0;
          font-size: 16px;
          font-weight: 500;
          color: $text-primary;
        }
      }

      .toolbar-right {
        display: flex;
        gap: 8px;
      }
    }

    // 图片网格样式
    .image-grid {
      padding: 16px;
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
      gap: 16px;
      min-height: 100px;
    }
  }
}

// 响应式调整
@media screen and (max-width: $breakpoint-sm) {
  .upload-container {
    padding: 16px;

    .upload-zone {
      padding: 16px;

      .uploader {
        :deep(.el-upload-dragger) {
          height: 120px;
        }
      }
    }

    .image-section {
      padding: 16px;

      .image-grid {
        grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
        gap: 12px;
      }
    }
  }
}

// 相册表单样式
.cover-uploader {
  width: 100%;

  :deep(.el-upload) {
    width: 100%;
    cursor: pointer;
  }

  .cover-container {
    position: relative;
    width: 100%;
    height: 200px;
    border-radius: 8px;
    background: $bg-light;
    overflow: hidden;
    transition: all 0.2s ease;
    border: 2px dashed transparent;

    &:hover {
      .upload-overlay {
        opacity: 1;
      }
    }

    &:not(.has-image) {
      border-color: rgba($color-primary, 0.2);
      border-style: dashed;
      border-width: 2px;

      &:hover {
        border-color: $color-primary;
        background: linear-gradient(135deg, rgba($color-primary, 0.05), rgba($color-primary, 0.08));
      }

      .upload-overlay {
        opacity: 1;
        background: transparent;
        color: $text-primary;

        .upload-icon {
          font-size: 32px;
          margin-bottom: 8px;
          color: rgba($color-primary, 0.6);
        }

        span {
          color: $text-primary;
          font-weight: 500;
        }
      }
    }

    .cover-preview {
      width: 100%;
      height: 100%;

      :deep(.el-image__inner) {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      .image-error {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        background: $bg-light;
        color: $text-secondary;
        font-size: 32px;
      }
    }

    .upload-overlay {
      position: absolute;
      inset: 0;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      background: rgba(0, 0, 0, 0.6);
      color: white;
      opacity: 0;
      transition: all 0.2s ease;

      .upload-icon {
        font-size: 24px;
        margin-bottom: 4px;
      }

      span {
        font-size: 14px;
        font-weight: 500;
      }
    }
  }
}

.w-full {
  width: 100%;
}

:deep(.el-input-number) {
  width: 100%;
}

// 筛选按钮样式
.filter-btn {
  background: $bg-base;
  border: 1px solid $border-light;
  color: $text-secondary;
  transition: all 0.3s ease;

  .el-icon {
    margin-right: 4px;
    transition: transform 0.3s ease;
  }

  &:hover {
    color: $color-primary;
    border-color: $color-primary;
    background: rgba($color-primary, 0.05);
  }

  &.is-active {
    color: $color-primary;
    border-color: $color-primary;
    background: rgba($color-primary, 0.1);

    .el-icon {
      transform: rotate(180deg);
    }
  }
}

// 优化搜索弹窗样式
:deep(.search-dialog) {
  .el-dialog__header {
    margin: 0;
    padding: 20px 20px 0;
    border-bottom: none;

    .el-dialog__title {
      font-size: 18px;
      font-weight: 600;
      color: $text-primary;
    }
  }

  .el-dialog__body {
    padding: 20px;
  }

  .search-form {
    .el-form-item {
      margin-bottom: 20px;

      &:last-child {
        margin-bottom: 0;
      }

      .el-form-item__label {
        padding-bottom: 8px;
        font-size: 14px;
        color: $text-secondary;
        font-weight: 500;
      }

      .el-input {
        .el-input__wrapper {
          box-shadow: 0 0 0 1px $border-light;
          transition: all 0.3s ease;

          &:hover {
            box-shadow: 0 0 0 1px $color-primary;
          }

          &.is-focus {
            box-shadow: 0 0 0 1px $color-primary;
          }
        }

        .el-input__prefix {
          color: $text-secondary;
        }
      }

      .el-radio-group {
        width: 100%;
        display: flex;
        gap: 8px;

        .el-radio-button {
          flex: 1;

          .el-radio-button__inner {
            width: 100%;
            border-radius: 4px;
            border: 1px solid $border-light;
            background: transparent;
            transition: all 0.3s ease;

            &:hover {
              border-color: $color-primary;
              color: $color-primary;
            }
          }

          &.is-active {
            .el-radio-button__inner {
              background: $color-primary;
              border-color: $color-primary;
              box-shadow: none;
              color: white;

              &:hover {
                color: white;
                background: color.adjust($color-primary, $lightness: -5%);
              }
            }
          }
        }
      }
    }
  }

  .dialog-footer {
    padding: 20px;
    margin: 0;
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    border-top: 1px solid $border-lighter;
  }
}

// 移除原有的搜索面板相关样式
.page-content {
  position: relative;
  display: flex;
  flex-direction: column;
  height: 100%;
}

// 使用 Element Plus 的内置提示样式类
:deep(.el-form-item__tip) {
  font-size: 12px;
  line-height: 1.4;
  color: var(--el-text-color-secondary);
  opacity: 0.6; // 降低不透明度使颜色更淡
  margin-top: 4px;
}

.image-card {
  position: relative;

  &.is-uploading {
    .el-image {
      opacity: 0.6;
    }

    .image-actions {
      display: none;
    }
  }

  .upload-progress {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 1;
  }

  .image-actions {
    position: absolute;
    top: 8px;
    right: 8px;
    opacity: 0;
    transition: all 0.3s ease;
    z-index: 2;

    .action-group {
      background: rgba(255, 255, 255, 0.9);
      border-radius: 20px;
      padding: 2px;
      backdrop-filter: blur(4px);
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
      display: flex;
      gap: 2px;

      .el-button {
        width: 32px;
        height: 32px;
        padding: 0;
        background: rgba(255, 255, 255, 0.9);
        border: none;
        backdrop-filter: blur(4px);
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
        transition: all 0.2s ease;

        &.el-button--danger {
          color: $color-danger;

          &:hover {
            background: rgba(255, 255, 255, 0.95);
            color: color.adjust($color-danger, $lightness: -10%);
            transform: scale(1.1);
          }
        }

        .el-icon {
          font-size: 16px;
        }

        &:active {
          transform: scale(0.95);
        }
      }
    }
  }

  &:hover {
    .image-actions {
      opacity: 1;
    }
  }
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid $border-lighter;

  .header-left {
    display: flex;
    align-items: center;
    gap: 16px;

    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 600;
      color: $text-primary;
    }
  }
}

// 已上传图片列表样式
.image-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  gap: 16px;
  padding: 16px;
  min-height: 200px;

  .image-item {
    .image-card {
      position: relative;
      aspect-ratio: 1;
      border-radius: 8px;
      overflow: hidden;
      background: $bg-light;
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);

        .image-info,
        .image-actions {
          opacity: 1;
        }

        .el-image :deep(img) {
          transform: scale(1.05);
        }
      }

      .el-image {
        width: 100%;
        height: 100%;

        :deep(img) {
          transition: transform 0.3s ease;
        }
      }

      .image-info {
        position: absolute;
        left: 0;
        right: 0;
        bottom: 0;
        padding: 12px;
        background: linear-gradient(to top, rgba(0, 0, 0, 0.8), transparent);
        color: white;
        opacity: 0;
        transition: opacity 0.3s ease;
        z-index: 1;

        .name {
          display: block;
          font-size: 14px;
          margin-bottom: 4px;
          @include text-ellipsis;
        }

        .size {
          font-size: 12px;
          opacity: 0.8;
        }
      }

      .image-actions {
        position: absolute;
        top: 8px;
        right: 8px;
        opacity: 0;
        transition: opacity 0.3s ease;
        z-index: 2;

        .el-button-group {
          background: rgba(255, 255, 255, 0.9);
          border-radius: 20px;
          padding: 2px;
          backdrop-filter: blur(4px);
          box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
        }

        .el-button {
          width: 32px;
          height: 32px;
          padding: 0;
          font-size: 14px;
        }
      }
    }
  }

  // 空状态样式
  .empty-state {
    grid-column: 1 / -1;
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 300px;

    :deep(.el-empty) {
      padding: 40px 0;
    }
  }
}

// 搜索框样式
.search-box {
  position: relative;
  width: 40px;
  height: 32px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  margin-left: 8px;

  &.is-active {
    width: 240px;

    .el-input {
      opacity: 1;
      transform: translateX(0);
      pointer-events: all;
    }

    .search-trigger {
      opacity: 0;
      pointer-events: none;
    }
  }

  .el-input {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    opacity: 0;
    transform: translateX(20px);
    pointer-events: none;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

    :deep(.el-input__wrapper) {
      box-shadow: 0 0 0 1px rgba($color-primary, 0.1);
      background: $bg-light;
      height: 32px;
      line-height: 32px;

      &:hover {
        box-shadow: 0 0 0 1px rgba($color-primary, 0.2);
      }

      &.is-focus {
        box-shadow: 0 0 0 1px $color-primary;
        background: white;
      }
    }
  }

  .search-trigger {
    position: absolute;
    left: 0;
    top: 0;
    width: 32px;
    height: 32px;
    transition: all 0.3s ease;
    background: transparent;
    border: none;
    color: $text-secondary;
    padding: 0;
    display: flex;
    align-items: center;
    justify-content: center;

    &:hover {
      color: $color-primary;
      background: rgba($color-primary, 0.1);
    }

    &.hide {
      opacity: 0;
      pointer-events: none;
    }

    .el-icon {
      font-size: 16px;
    }
  }
}

// 重命名弹窗样式
:deep(.rename-dialog) {
  .el-dialog__header {
    margin: 0;
    padding: 24px 24px 0;
    border-bottom: none;

    .el-dialog__title {
      font-size: 18px;
      font-weight: 600;
      color: $text-primary;
    }
  }

  .el-dialog__body {
    padding: 24px;
  }

  .el-dialog__footer {
    padding: 0 24px 24px;
    border-top: none;
  }

  .rename-content {
    display: flex;
    flex-direction: column;
    gap: 20px;

    .image-preview {
      display: flex;
      justify-content: center;
      margin-bottom: 8px;

      .preview-image {
        width: 120px;
        height: 120px;
        border-radius: 8px;
        overflow: hidden;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        border: 2px solid $border-lighter;

        :deep(.el-image__inner) {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }

        .image-error {
          width: 100%;
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
          background: $bg-light;
          color: $text-secondary;
          font-size: 32px;
        }
      }
    }

    .rename-form {
      .el-form-item {
        margin-bottom: 20px;

        &:last-child {
          margin-bottom: 0;
        }

        .el-form-item__label {
          padding-bottom: 8px;
          font-size: 14px;
          color: $text-secondary;
          font-weight: 500;
        }

        .name-input-wrapper {
          display: flex;
          align-items: stretch;
          border: 1px solid $border-light;
          border-radius: 8px;
          overflow: hidden;
          background: white;
          transition: border-color 0.2s ease;

          &:hover {
            border-color: rgba($color-primary, 0.5);
          }

          &:focus-within {
            border-color: $color-primary;
            box-shadow: 0 0 0 3px rgba($color-primary, 0.08);
          }

          .prefix-input {
            flex: 1;
            border: none;
            border-radius: 0;

            :deep(.el-input__wrapper) {
              box-shadow: none;
              border: none;
              border-radius: 0;
              padding: 0 12px;
              background: transparent;
              min-height: 40px;

              &:hover,
              &.is-focus {
                box-shadow: none;
                background: transparent;
              }

              .el-input__inner {
                padding: 0;
                font-size: 14px;
                line-height: 1.5;
              }

              // 隐藏清空按钮，避免抖动
              .el-input__suffix {
                display: none;
              }
            }
          }

          .suffix-display {
            display: flex;
            align-items: center;
            padding: 0 16px;
            background: linear-gradient(135deg, #f8f9fa 0%, #f1f3f4 100%);
            color: $text-secondary;
            font-size: 14px;
            font-weight: 500;
            border-left: 1px solid rgba($border-light, 0.8);
            white-space: nowrap;
            user-select: none;
            min-height: 40px;
            position: relative;

            &::before {
              content: '';
              position: absolute;
              left: 0;
              top: 50%;
              transform: translateY(-50%);
              width: 1px;
              height: 20px;
              background: linear-gradient(to bottom, transparent, $border-light, transparent);
            }
          }
        }

        .input-tip {
          margin-top: 8px;
          font-size: 12px;
          color: rgba($text-secondary, 0.7);
          line-height: 1.4;
          padding: 8px 12px;
          background: rgba($color-primary, 0.04);
          border-radius: 6px;
          border-left: 3px solid rgba($color-primary, 0.2);
        }
      }
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    margin: 0;
    padding: 0;
  }
}

// 移动端适配
@media screen and (max-width: $breakpoint-sm) {
  :deep(.rename-dialog) {
    width: 90% !important;
    margin: 0 auto;

    .el-dialog__header {
      padding: 20px 20px 0;
    }

    .el-dialog__body {
      padding: 20px;
    }

    .el-dialog__footer {
      padding: 0 20px 20px;
    }

    .rename-content {
      gap: 16px;

      .image-preview {
        .preview-image {
          width: 100px;
          height: 100px;
        }
      }

      .rename-form {
        .el-form-item {
          margin-bottom: 16px;

          .name-input-wrapper {
            .prefix-input {
              :deep(.el-input__wrapper) {
                padding: 0 10px;
                min-height: 36px;

                .el-input__inner {
                  padding: 0;
                  font-size: 13px;
                }

                .el-input__suffix {
                  display: none;
                }
              }
            }

            .suffix-display {
              padding: 0 12px;
              font-size: 13px;
              min-height: 36px;
            }
          }

          .input-tip {
            font-size: 11px;
            padding: 6px 10px;
            margin-top: 6px;
          }
        }
      }
    }

    .dialog-footer {
      flex-direction: column;
      gap: 8px;

      .el-button {
        width: 100%;
      }
    }
  }
}
</style>
